import React, { useState, useRef, useEffect } from 'react';
import { Tabs, Avatar, List, Button, Input } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import _ from 'lodash'
import { nanoid } from 'nanoid'
import dayjs from 'dayjs'
import axios from 'axios'
const { Search } = Input;



function useGetList(){

  const [list, setList] = useState([])
  useEffect(() => {
    async function getList() {
      let res = await axios.get('http://localhost:3004/list')
      console.log(res.data);
      setList(_.orderBy(res.data, (dateObj) => {
        return new Date(dateObj.ctime);
      }, 'desc'))
    }

    getList()
  }, [])
  return {
    list,
    setList
  }
}

function App() {
  const items = [
    {
      key: '1',
      label: '最新',
    },
    {
      key: '2',
      label: '最热',
    },
  ];
  
  const curUser = {
    uid: '300010003',
    avatar: '',
    uname: '王五'
  }
  
  let {list, setList} = useGetList()

  function delComment(item) {
    console.log(item.rpid);
    let filterList = list.filter(listItem => listItem.rpid !== item.rpid)
    setList(filterList)
    return item.rpid
  }

  const onChange = (key) => {
    let filterList = []
    if (key === '1') {
      filterList = _.orderBy(list, (dateObj) => {
        return new Date(dateObj.ctime).getTime();
      }, 'desc')
    } else if (key === '2') {
      filterList = _.orderBy(list, ['like'], 'desc')
    }
    setList(filterList)
  };





  // 发布评论
  let [inpVal, setInpVal] = useState('')
  const inputRef = useRef(null);
  function addComment(val) {
    let newComment = {
      rpid: nanoid(),
      user: {
        ...curUser
      },
      ctime: dayjs().format('YYYY-MM-DD hh:mm'), // '2023-12-28 00:00',
      content: val,
      like: 0,
    }

    setList([newComment, ...list])
    // 清空，并重新聚焦
    setInpVal('')
    // @ts-ignore
    inputRef.current.focus();
    return newComment
  }
  function handleInp(e) {
    let val = e.target.value
    setInpVal(val)
  }

  function pushComment(e) {
    let val = e.target.value
    addComment(val)
  }

  const onSearch = (value, _e, info) => {
    let val = value
    addComment(val)
  };

  return (
    <div>
      <Search placeholder="请填写"
        enterButton="发布"
        onPressEnter={pushComment}
        onSearch={onSearch}
        onChange={handleInp}
        value={inpVal}
        ref={inputRef}
      />

      <Tabs onChange={onChange}
        items={items.map((item, i) => {
          return {
            label: `${item.label}`,
            key: item.key,
          };
        })}
      />
      <List
        itemLayout="horizontal"
        dataSource={list}
        renderItem={(item, index) => (
          <List.Item actions={[curUser.uid === item.user.uid ? <Button onClick={() => {
            delComment(item)
          }} key="del" icon={<DeleteOutlined />}></Button> : '']}>
            <List.Item.Meta
              avatar={<Avatar src={`https://xsgames.co/randomusers/avatar.php?g=pixel&key=${index}`} />}
              title={item.content}
              description={`${item.ctime} 点赞数：${item.like}`}
            />
          </List.Item>
        )}
      />
    </div>
  )
}

export default App;